package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author :XingJiaCheng
 * @date :2022-09-19-10:09
 * @description
 **/
@Slf4j
@WebFilter(filterName = "loginFilter")
public class LoginCheckFilter implements Filter {

    private String[] authUrl = new String[]{
            "/favicon.ico",
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/sendMsg",
            "/user/login",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("loginCheckFilter....");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("请求url:{}",requestURI);
        boolean isAuth = checkAuthUrl(requestURI);
        if (isAuth){
            filterChain.doFilter(request,response);
            return;
        }
        if ((request.getSession().getAttribute("employee")!=null)){
            log.info("[登录检查,已经登录 id:{}]",request.getSession().getAttribute("employee"));
            Long userId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        if ((request.getSession().getAttribute("user")!=null)){
            log.info("[登录检查,已经登录 id:{}]",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("未登录....uri:{}",requestURI);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private boolean checkAuthUrl(String requestURI) {
        for (String url : authUrl) {
            if (antPathMatcher.match(url,requestURI)){
                return true;
            }

        }
        return false;
    }
}
